import { Component, _decorator, Sprite, NodeEventType, Vec3, EventTouch, Vec2, UITransform, AudioClip } from "cc";
import { EAreaID, EPokerState, ESuit } from "../../constant/GameEnum";
import GameCtrl from "../../model/GameCtrl";
import ModelGame from "../../model/ModelGame";
import PlayPokerGroupVo from "../../model/PlayPokerGroupVo";
import PokerVo from "../../model/PokerVo";
import { AudioSys } from "../../utils/AudioUtils";
import { ClickLock } from "../../utils/DecoratorUtils";
import { GameView } from "../gameView/GameView";
const { ccclass, property } = _decorator;
const SUIT = [0, 2, 3, 1];
@ccclass("UIPoker")
export default class UIPoker extends Component {
  @property(Sprite)
  imgBg: Sprite = null;
  @property(AudioClip)
  clickAudio: AudioClip;
  private poker: PokerVo = null;
  private oldZindex: number = -1;
  private gameView: GameView = null;
  private isTouchStart: boolean = false;
  private isDragStart: boolean = false;
  private startToDragSchedule: Function = null;
  private targetPos: Vec3 = null;
  private scheduleMoveToTargetPos: Function = null;
  onLoad() {
    this.node.on(NodeEventType.TOUCH_START, this.onStart, this);
    this.node.on(NodeEventType.TOUCH_MOVE, this.onMove, this);
    this.node.on(NodeEventType.TOUCH_END, this.onEnd, this);
    this.node.on(NodeEventType.TOUCH_CANCEL, this.onEnd, this);
  }
  start(): void {}

  onDestroy(): void {
    this.node.off(NodeEventType.TOUCH_START, this.onStart, this);
    this.node.off(NodeEventType.TOUCH_MOVE, this.onMove, this);
    this.node.off(NodeEventType.TOUCH_END, this.onEnd, this);
    this.node.off(NodeEventType.TOUCH_CANCEL, this.onEnd, this);
  }
  init(poker: PokerVo, view: GameView) {
    poker.setView = this;
    this.gameView = view;
    this.poker = poker;
    this.setDir();
  }
  private setDir(): void {
    if (this.poker.state == EPokerState.CLOSE) {
      this.imgBg.spriteFrame = this.imgBg.spriteAtlas.getSpriteFrame("card");
    } else {
      this.imgBg.spriteFrame = this.imgBg.spriteAtlas.getSpriteFrame(`card_${SUIT[this.poker.suit]}_${this.poker.point - 1}`);
    }
  }
  public refresh(): void {
    this.setDir();
  }

  @ClickLock(0.4)
  private onStart(event: EventTouch): void {
    if (this.isTouchStart) {
      return;
    }

    // AudioSys.instance.playSound(this.clickAudio);
    this.isTouchStart = true;
    this.isDragStart = false;
    this.startToDragSchedule = () => {
      if (this.gameView.isOpenByState(this.poker)) {
        if (!this.gameView.isOpenArea(this.poker) || this.poker.parent.topPoker == this.poker) {
          this.isDragStart = true;
        }
      }
    };
    this.scheduleOnce(this.startToDragSchedule, 0.2);
  }

  private onMove(event: EventTouch): void {
    if (!this.isTouchStart) {
      return;
    }
    if (this.isDragStart) {
      let isFirst: boolean = this.targetPos == null;
      let newTouchLocation = event.getUILocation();
      this.targetPos = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(newTouchLocation.x, newTouchLocation.y, 0));

      if (isFirst) {
        this.scheduleMoveToTargetPos = () => {
          if (this.isDragStart) {
            let nodePos: Vec3 = this.node.getPosition();
            if (!(nodePos.x == this.targetPos.x && nodePos.y == this.targetPos.y)) {
              let dx = this.targetPos.x - nodePos.x;
              let dy = this.targetPos.y - nodePos.y;
              if (dx * dx + dy * dy < 5) {
                this.moveNode(this.targetPos.x, this.targetPos.y);
              } else {
                let sx = dx / 5;
                let sy = dy / 5;
                this.moveNode(nodePos.x + sx, nodePos.y + sy);
              }
            }
          }
        };
        this.schedule(this.scheduleMoveToTargetPos, 0);
      }
    }
  }

  private onEnd(): void {
    if (!this.isTouchStart) {
      return;
    }
    this.isTouchStart = false;
    this.unschedule(this.startToDragSchedule);
    this.startToDragSchedule = null;
    this.targetPos = null;
    this.unschedule(this.scheduleMoveToTargetPos);
    this.scheduleMoveToTargetPos = null;
    if (this.isDragStart) {
      this.node.setSiblingIndex(this.oldZindex);
      this.isDragStart = false;
      this.gameView.onDragUIPoker(this.poker);
    } else {
      this.gameView.onClickUIPoker(this.poker);
    }
  }

  //拖拽时的移动
  private moveNode(x: number, y: number): void {
    this.gameView.changeAreaOrder(this.poker);
    this.oldZindex = this.node.getSiblingIndex();
    this.node.setSiblingIndex(this.gameView.changePokerInGroupOrder(this.poker));
    this.node.setPosition(x, y);
    let pg = this.poker.parent;
    if (pg instanceof PlayPokerGroupVo) {
      let pokerIndex = pg.getIndexByGroup(this.poker);
      if (pg.getConnectPoker(this.poker).length > 1) {
        for (let index = pokerIndex + 1; index < pg.pokers.length; index++) {
          let poker: PokerVo = pg.getPokerByIndex(index);
          let node = poker.getView.node;
          node.setSiblingIndex(this.node.getSiblingIndex() + index);
          node.setPosition(x, y - 30 * (index - pokerIndex));
        }
      }
    }
  }
}
